<template>
  <div>
    <!-- 标题 -->
    <el-card shadow="never" v-if="flag">
      <div slot="header" class="clearfix">
        <h3>文章列表</h3>
      </div>

      <!-- 下拉选择框 -->
      <div  class="artlistselect">
        <div>
          <span>文章分类</span>
          <el-select v-model="astilist.cate_id" placeholder="请选择分类">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.cate_name"
              :value="item.id">
            </el-option>
          </el-select>
          <span>发布状态</span>
          <el-select v-model="astilist.state" placeholder="请选择状态">
            <el-option
               v-for="item in options2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          <el-button type="primary"  @click="search">筛选</el-button>
          <el-button type="primary"  plain @click="reset">重置</el-button>
        </div>
        <div>
            <el-button type="primary" @click="flag = false">发表文章</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%">

        <el-table-column
          prop="title"
          label="文章标题"
          >
        </el-table-column>
        <el-table-column
          prop="cate_name"
          label="分类">
        </el-table-column>
        <el-table-column
          label="发表时间">
          <template slot-scope="scope">
            {{scope.row.pub_date | timeFormat}}
          </template>

        </el-table-column>
        <el-table-column
          prop="state"
          label="状态">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
        <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5,10,20,30]"
        :page-size="astilist.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        >
      </el-pagination>
    </el-card>

    <!-- 添加文章页面 -->
    <el-card shadow="never" v-else>
      <div slot="header" class="clearfix">
        <h3>写文章</h3>
        <i class="el-icon-close" @click="outbun"></i>
      </div>

      <el-form ref="form2"  :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-Select v-model="form.cate_id" placeholder="请选择分类" class="select">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item.cate_name"
              :value="item.id">
            </el-option>
          </el-Select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor
            :options='editorOption'
            v-model="form.content"
            ref="myQuillEditor"
            >
        </quill-editor>

        </el-form-item>
        <el-form-item label="文章封面">
           <el-button @click="a" size="small">选择封面</el-button>
          <input type="file" id="fileImage" name="fileImage" @change="showImg" accept="image/*" style="display:none">
          <div class="headerimg">
            <img v-if="form.cover_img" id="img1" :src="form.cover_img" alt="" >
            <span v-else>点击上方"选择封面"</span>

          </div>
        </el-form-item>

        <!-- 按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submit('已发布')">发布</el-button>
          <el-button @click="submit('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import { getartlist, postartlist, delartlistinfo, getartlistinfo, putartlistinfo } from '@/api/artlist'
import dayjs from 'dayjs'
import { getarticate } from '@/api/articate'
import { quillEditor } from 'vue-quill-editor'

import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'BigEventIndex',
  components: {
    quillEditor
  },
  data () {
    return {
      img: false,
      flag: true,
      options: [],
      astilist: {
        pagenum: 1,
        pagesize: 10,
        state: '',
        cate_id: ''
      },
      total: 0,
      currentPage: 0,
      tableData: [],
      form: {
        title: '',
        cover_img: null,
        cate_id: '',
        state: '',
        content: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        cate_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      },
      options2: [{
        value: '已发布',
        label: '已发布'
      }, {
        value: '草稿',
        label: '草稿'
      }],

      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除文本格式
            ['image', 'video'] // 链接、图片、视频
          ]
        },
        placeholder: '这里可以填写内容'

      }
    }
  },
  created () {
    this.getartlist()
    this.getarticate()
  },

  mounted () {
  },

  methods: {
    getImageFileFromUrl (url, imageName, callback) {
      fetch(url)
        .then((res) => {
          return res.blob()
        })
        .then((blob) => {
          const imgFile = new File([blob], imageName, { type: 'image/jpeg' })
          callback(imgFile)
        })
    },

    async getarticate () {
      const { data } = await getarticate()
      this.options = data.data
    },
    handleSizeChange (val) {
      this.astilist.pagesize = val
      this.getartlist()
    },
    handleCurrentChange (val) {
      this.astilist.pagenum = val
      this.getartlist()
    },
    async getartlist () {
      const { data: res } = await getartlist(this.astilist)
      this.tableData = res.data
      this.total = res.total
    },

    async submit (state) {
      await this.$refs.form2.validate()
      this.form.state = state
      let data = {}
      if (this.form.id) {
        // 修改 判断是否修改封面
        if (typeof (this.form.cover_img) === 'string') {
          const imgName = this.form.cover_img.split('/').pop()
          this.getImageFileFromUrl(this.form.cover_img, imgName, async (file) => {
            this.form.cover_img = file
            data = await putartlistinfo(this.form)
            this.$message.success(data.data.message)
            this.clearData()
            this.getartlist()
          })
        } else {
          data = await putartlistinfo(this.form)
          console.log(data)
          this.$message.success(data.data.message)
          this.clearData()
          this.getartlist()
        }
      } else {
        data = await postartlist(this.form)
        this.$message.success(data.data.message)
        this.clearData()
        this.getartlist()
      }
      this.img = false
      this.flag = true
    },

    // 数据清空
    clearData () {
      this.form = {
        title: '',
        cover_img: '',
        cate_id: '',
        state: '',
        content: ''
      }
    },
    a () {
      document.getElementById('fileImage').click()
    },
    showImg () {
      this.form.cover_img = document.getElementById('fileImage').files[0]
      if (window.FileReader) {
        const reader = new FileReader()
        reader.readAsDataURL(this.form.cover_img)
        reader.onloadend = function (e) {
          document.getElementById('img1').setAttribute('src', e.target.result)
        }
      }
      this.img = true
    },
    async handleDelete (index, row) {
      const { data } = await delartlistinfo(row.id)
      this.$message.success(data.message)
      this.getartlist()
    },
    async search () {
      const { data } = await getartlist(this.astilist)
      this.tableData = data.data
      this.total = data.total
      this.$message.success(data.message)
    },
    reset () {
      this.astilist = {
        pagenum: 1,
        pagesize: 10,
        state: '',
        cate_id: ''
      }
      this.getartlist()
    },
    outbun () {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form = {}
        this.flag = true
      }).catch((e) => {

      })
    },
    async handleEdit (id, row) {
      const { data } = await getartlistinfo(row.id)
      this.form = data.data
      this.form.cover_img = 'http://big-event-vue-api-t.itheima.net' + data.data.cover_img
      this.flag = false
    }

  },
  filters: {
    timeFormat: function (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .ql-container {
  height: 15rem;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.artlistselect {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 5rem;
  width: 100%;
}
.el-select {
  margin: 0 1rem;
}

 .avatar-uploader .el-upload {
    border: 1px dashed #2e2c2c;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .headerimg {
    width: 25rem;
    height: 13rem;
    background-color: #efefef;
    margin-top: 1rem;
    text-align: center;
    line-height: 13rem;
    img {
      width: 100%;
      height: 100%;
    }
    span{
      color:  #5d5a5a;
    }
  }
  .select {
    width: 100%;
    margin: 0;

  }
.el-pagination {
  margin-top: 1rem;
}

</style>
